﻿using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace Moonlite.CommandPrompt
{
    public class ArgumentParser
    {
        [DllImport("shell32.dll", SetLastError = true)]
        private static extern IntPtr CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)]string lpCmdLine, out int pNumArgs);
        private static StringCollection Arguments { get; set; }
        public int Count
        {
            get { return Arguments.Count; }
        }

        public string this[int index]
        {
            get { return Arguments.Count > index ? Arguments[index] : null; }
        }

        public bool Exists(string argument)
        {
            return Arguments.Contains(argument);
        }

        public ArgumentParser(string commandLine)
        {
            Arguments = new StringCollection();
            int argc;
            var argv = CommandLineToArgvW(commandLine, out argc);
            if (argv == IntPtr.Zero)
            {
                throw new Win32Exception();
            }

            try
            {
                for (var i = 0; i < argc; i++)
                {
                    var p = Marshal.ReadIntPtr(argv, i * IntPtr.Size);
                    Arguments.Add(Marshal.PtrToStringUni(p));
                }
            }
            finally
            {
                Marshal.FreeHGlobal(argv);
            }
        }
    }
}
